package red;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.common.util.concurrent.RateLimiter;  

public class RateLimiterDemo {  
    public static void main(String[] args) {  
        //testNoRateLimiter();  
       // testWithRateLimiter(); 
        
        testRateLimit();
    }  
    
    public static void testRateLimit(){
    	 String start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    	    RateLimiter limiter = RateLimiter.create(2.0); // 这里的1表示每秒允许处理的量为1个
    	    for (int i = 1; i <= 10; i++) { 
    	        limiter.acquire();// 请求RateLimiter, 超过permits会被阻塞
    	        System.out.println("call execute.." + i);
    	    }
    	    String end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    	    System.out.println("start time:" + start);
    	    System.out.println("end time:" + end);

    }
   
    public static void testNoRateLimiter() {  
        Long start = System.currentTimeMillis();  
        for (int i = 0; i < 100; i++) {  
            System.out.println("call execute.." + i);  
              
        }  
        Long end = System.currentTimeMillis();  
          
        System.out.println(end - start);  
          
    }  
      
    public static void testWithRateLimiter() {  
        Long start = System.currentTimeMillis();  
        RateLimiter limiter = RateLimiter.create(10.0); // 每秒不超过10个任务被提交  
        for (int i = 0; i < 100; i++) {  
            limiter.acquire(); // 请求RateLimiter, 超过permits会被阻塞  
            System.out.println("call execute.." + i);  
              
        }  
        Long end = System.currentTimeMillis();  
          
        System.out.println(end - start);  
          
    }  
      
}  

